<?php

namespace UserModule\service;

use Config\MysqlLocal;
use UserModule\m\RoleOrm;
use UserModule\m\UserOrm;

/**
 * 用户模块 表初始化
 * Class UserInit
 * @package UserModule\service
 */
class ModelTableInit
{
    /**
     * 创建表 用户表
     * 初始化一条admin数据
     * @return bool
     */
    public function initUser()
    {
        $tableName = UserOrm::USER_TABLE_NAME;
        $db = MysqlLocal::getDB();
        $querySql = <<<SQL
SHOW TABLES LIKE '{$tableName}'
SQL;
        $result = $db->query($querySql)->fetchAll();
        if (null != $result) {
            return false;
        }

        $querySql = <<<SQL
CREATE TABLE `{$tableName}` (
  `uid` BIGINT(20) unsigned NOT NULL AUTO_INCREMENT,
  `rid` int(10) DEFAULT '2' COMMENT '角色',
  `home_url` varchar(255) DEFAULT '' COMMENT '个人首页空间',
  `user_name` varchar(50) NOT NULL DEFAULT '' COMMENT '用户名',
  `password` char(32) NOT NULL DEFAULT '' COMMENT '加密密码',
  `salt` char(10) NOT NULL COMMENT '随机加密码',
  `name` varchar(50) NOT NULL COMMENT '姓名',
  `phone` char(20) NOT NULL COMMENT '手机号码',
  `avatar` varchar(255) NOT NULL COMMENT '头像地址',
  PRIMARY KEY (`uid`),
  KEY `username` (`user_name`),
  KEY `phone` (`phone`)
) ENGINE=InnoDB COMMENT='会员表';
INSERT INTO `{$tableName}`(`uid`, `rid`, `user_name`, `password`, `salt`, `name`, `phone`, `avatar`) VALUES (1, 1, 'admin', 'admin', 'qwer', 'admin', '182********', '0');
SQL;
        $db->query($querySql)->execute();
        return true;
    }

    /**
     * 创建表 角色表
     * @return bool
     */
    public function initRole()
    {
        $tableName = RoleOrm::ROLE_TABLE_NAME;
        $db = MysqlLocal::getDB();
        $querySql = <<<SQL
SHOW TABLES LIKE '{$tableName}'
SQL;
        $result = $db->query($querySql)->fetchAll();
        if (null != $result) {
            return false;
        }

        $querySql = <<<SQL
CREATE TABLE `{$tableName}` (
  `rid` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL DEFAULT '' COMMENT '角色名',
  `note` char(32) NOT NULL DEFAULT '' COMMENT '备注',
  PRIMARY KEY (`rid`)
) ENGINE=InnoDB COMMENT='角色表';
INSERT INTO `{$tableName}`(`rid`, `name`, `note`) VALUES (1, 'admin', '管理员');
INSERT INTO `{$tableName}`(`rid`, `name`, `note`) VALUES (2, 'guest', '游客');
INSERT INTO `{$tableName}`(`rid`, `name`, `note`) VALUES (3, 'vip', '普通会员');
SQL;
        $db->query($querySql)->execute();
        return true;
    }
}